package estore.src.estore.service;
import estore.src.estore.model.Product;
import java.util.*;
import java.io.*;
import java.util.Properties;

/**
 * 商品数据存储类，专门负责数据的持久化操作
 */
public class ProductStorer {
    private String dataFilePath;

    public ProductStorer() {
        loadConfig();
    }

    /**
     * 加载配置文件
     */
    private void loadConfig() {
        Properties props = new Properties();
        File configFile = new File("config.properties");

        if (!configFile.exists()) {
            // 如果配置文件不存在，使用默认值并创建配置文件
            dataFilePath = "products.dat";
            saveDefaultConfig();
            System.out.println("配置文件不存在，已创建默认配置");
            return;
        }

        try (InputStreamReader reader = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(reader);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
            System.out.println("配置文件加载成功，数据文件路径: " + dataFilePath);
        } catch (IOException e) {
            System.err.println("加载配置文件失败: " + e.getMessage());
            dataFilePath = "products.dat"; // 使用默认值
        }
    }

    /**
     * 保存默认配置到文件
     */
    private void saveDefaultConfig() {
        Properties props = new Properties();
        props.setProperty("data.file.path", "products.dat");

        try (OutputStreamWriter writer = new OutputStreamWriter(
                new FileOutputStream("config.properties"), "UTF-8")) {
            props.store(writer, "电子商店系统配置");
        } catch (IOException e) {
            System.err.println("保存默认配置失败: " + e.getMessage());
        }
    }

    /**
     * 保存商品数据到文件
     */
    public void saveData(Map<String, Product> products) {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(dataFilePath))) {
            oos.writeObject(products);
            System.out.println("数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }

    /**
     * 从文件加载商品数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Product> loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在，将创建新文件");
            return new HashMap<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(dataFilePath))) {
            Map<String, Product> loadedProducts = (Map<String, Product>) ois.readObject();
            System.out.println("数据已从 " + dataFilePath + " 加载，共 " + loadedProducts.size() + " 个商品");
            return loadedProducts;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载数据失败: " + e.getMessage());
            return new HashMap<>();
        }
    }

    /**
     * 备份数据文件
     */
    public boolean backupData() {
        System.out.println("\n=== 数据备份 ===");

        String sourceFile = dataFilePath;
        String backupFile = dataFilePath + ".bak";

        File source = new File(sourceFile);
        if (!source.exists()) {
            System.out.println("源数据文件不存在，无法备份！");
            return false;
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("数据备份成功！备份文件: " + backupFile);
            System.out.println("文件大小: " + source.length() + " 字节");
            return true;

        } catch (IOException e) {
            System.err.println("备份失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取数据文件路径
     */
    public String getDataFilePath() {
        return dataFilePath;
    }

    /**
     * 设置数据文件路径
     */
    public void setDataFilePath(String dataFilePath) {
        this.dataFilePath = dataFilePath;
    }
}